<template>
  <div class="ConfigTableForm">
    <el-form ref="mainRef" :model="tableFormData" v-if="visible" v-loading="loading" v-bind="config.formProps">
      <el-table row-key="__rowKey__" :data="tableFormData.data" style="width: 100%" border v-bind="config.tableProps">
        <el-table-column label="序号" type="index" width="60" fixed align="center" />

        <el-table-column :label="item.label" :prop="(item.prop as string)" v-for="(item, index) in config.columns"
          :key="(item.prop as string) + index" v-bind="item.columnProps">
          <template #header v-if="isRequire(item)">
            <span style="color: #f56c6c;">* </span>{{ item.label }}
          </template>
          <template #default="scope">
            <FormItem :item="item" v-model="scope.row[(item.prop as string)]" :mode="config.mode + '_TableForm'"
              :scope="scope" />
          </template>
        </el-table-column>

        <!-- 这里可以使用具名插槽替换掉默认内容 -->
        <slot name="table-action">
          <el-table-column fixed="right" label="操作" width="80" align="center">
            <template #default="scope">
              <el-button type="danger" size="small" @click.prevent="deleteRow(scope.$index)"
                :disabled="config.mode === 'look'">
                删除
              </el-button>
            </template>
          </el-table-column>
        </slot>

      </el-table>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import FormItem from '@/components/ConfigForm/src/item.vue'
import type { Config } from './type'
import type { Column } from '@/components/ConfigForm/src/type'
import { ref, nextTick, computed, watch, onMounted } from 'vue';
import { ElForm, ElTable, ElTableColumn, ElButton } from 'element-plus';

interface Props {
  modelValue: ObjectAny[] // 绑定对象
  config: Config // 组件配置
}
const props = withDefaults(defineProps<Props>(), {})
const mainRef = ref()

const loading = ref(false as boolean)
let visible = ref(false)
const reRender = () => {
  visible.value = false
  nextTick(() => {
    visible.value = true
  });
}

// 表单嵌套表格需要这种数据形式
const tableFormData = computed(() => {
  return { data: props.modelValue }
}) as ObjectAny

// 设置默认值
const setDefaultValue = () => {
  let newLines = props.modelValue.filter(line => !line.__rowKey__)
  if (!newLines.length) return
  let timestamp = +new Date()
  /** 判断字段是否需要设置默认值*/
  function isInvalid(validateValue: any, column: Column) {
    return (validateValue === undefined
      || validateValue === null
      || validateValue === ''
      || (Array.isArray(validateValue) && validateValue.length === 0))
      && column.value !== undefined
  }
  newLines.forEach((line, i) => {
    let concatLine = {} as ObjectAny
    props.config.columns.forEach(column => {
      if (isInvalid(line[(column.prop as string)], column)) {
        concatLine[(column.prop as string)] = column.value
      }
    })
    concatLine.__rowKey__ = `${timestamp}_${i}`
    Object.assign(line, concatLine)
  });
}
watch(props.modelValue, async () => {
  // loading.value = true
  // await nextTick()
  setDefaultValue()
  // await nextTick()
  // loading.value = false
}, {
  immediate: true,
  deep: false,
  flush: 'sync'
})

onMounted(() => {
  visible.value = true
})

// 删除行
const deleteRow = (index: number) => {
  // eslint-disable-next-line vue/no-mutating-props
  props.modelValue.splice(index, 1)
}

// 判断列是否必填
const isRequire = (item: ObjectAny) => {
  return Object.prototype.hasOwnProperty.call(item, 'rules') && item.rules.some((rule: ObjectAny) => rule.required)
}

defineExpose({ mainRef, reRender, setDefaultValue })
</script>
<style lang="scss" scoped>
:deep(.el-form) {
  .is-center .el-form-item__content {
    justify-content: center;
  }

  .el-form-item {
    margin-bottom: 0;
  }
}
</style>